package com.jianye.recycdona.control.http;

import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.jianye.recycdona.control.Apps;
import com.jianye.recycdona.model.fragment.home.bean.addressInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.jianye.recycdona.control.Apps.JSON;
import static com.jianye.recycdona.control.http.UserOkHttp.attachHttpGetParams;

public class ReserveHttp {

    private static final ReserveHttp reserveHttp=new ReserveHttp();

    private final Gson gson=common.getGson();

    private ReserveHttp() {
    }
    public static ReserveHttp getMyOkHttp() {
        return reserveHttp;
    }

    private static final OkHttpClient  client= common.getClient();



    /**
     * Post  存储数据到后台数据库
     * post(paretId,nameadd,phoneadd,cityadd,detaiadd);
     */
    public int  postAddresss(String parenId,String name,String phone,String city,String detaile) throws ExecutionException, InterruptedException {
        AddressThread callableThread = new AddressThread(parenId,name,phone,city,detaile);
        FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
        return 200;
    }
    class AddressThread implements Callable {

        String parentId,name, phone, city, detaile;

        public AddressThread(String parenId,String name, String phone, String city, String detaile) {
            this.parentId=parenId;
            this.name = name;
            this.phone = phone;
            this.city = city;
            this.detaile = detaile;
        }

        @Override
        public Object call() throws Exception {
            System.out.println(Thread.currentThread().getName());

            try {
                //传的json
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("parent_id",parentId);
                jsonObject.put("receiver",name);//收货人
                jsonObject.put("phone",phone);
                jsonObject.put("address",city);
                jsonObject.put("detai_address",detaile);
                String callStr = UserOkHttp.post(Apps.PostReserveInfo, jsonObject.toString());
                JSONObject call_json = new JSONObject(callStr);
                final String code = call_json.getString("status");
                System.out.print(code + "-------------------------------code");

            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }

            System.out.print("-------------------------------OK");
            return "ok";
        }

    }

    public  addressInfo.DataBean js = null;
    List<addressInfo.DataBean> addressDataList=new ArrayList<>();
    /**
     * Get 获取地址信息
     */
    public List<addressInfo.DataBean> getAddressInfo(String paretId,SharedPreferences sp) throws ExecutionException, InterruptedException {
        GetAddressinfo callableThread = new GetAddressinfo(paretId,sp);
        FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());

        return addressDataList;
    }


    class GetAddressinfo implements Callable {
        private String parentId;
        SharedPreferences sp;

        public GetAddressinfo(String parentId, SharedPreferences sp) {
            this.parentId = parentId;
            this.sp = sp;
        }

        @Override
        public Object call() throws Exception {

            //url拼接
            LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
            linkedHashMap.put("parentId", parentId);

            String url = attachHttpGetParams(Apps.GetReserveInfo, linkedHashMap);
            Log.e("url", "-------------------------------------->" + url);

            Request request = new Request.Builder()
                    .url(url)//请求接口。如果需要传参拼接到接口后面。
                    .build();//创建Request 对象
            Response response = null;
            response = client.newCall(request).execute();//得到Response 对象


            if (response.isSuccessful()) {

                try {
                    assert response.body() != null;
                    String msginfo = response.body().string();

                    Log.e("msg", "------------------------------------" + msginfo);
                    addressInfo fromJson = gson.fromJson(msginfo, addressInfo.class);

                    int listsize=fromJson.getData().size();
                    Log.d("listsize", "call: ----------------->"+listsize);

                    if (addressDataList!=null){//防止数据重复
                        addressDataList.clear();
                    }
                    for (int i=0;i<listsize;i++){

                        addressDataList.add(new addressInfo.DataBean(fromJson.getData().get(i).getAddress()
                                , fromJson.getData().get(i).getDetaiAddress(),fromJson.getData().get(i).getId(),
                                fromJson.getData().get(i).getParentId(),fromJson.getData().get(i).getPhone(),
                                fromJson.getData().get(i).getReceiver()));

                    }
//                    SharedPreferences.Editor editor = sp.edit();

//                    editor.putString("id", fromJson.getData().get(0).getId()+"");
//                    editor.putString("parenId", fromJson.getData().getParentId()+"");//用户ID
//                    editor.putString("username", fromJson.getData().getReceiver());//收货人
//                    editor.putString("phone", fromJson.getData().getPhone());//收货人电话号码
//                    editor.putString("detai", fromJson.getData().getDetaiAddress());//详细地址
//                    editor.apply();
                    Log.d("listsize", "------------------------------>" + fromJson.getStatus() + fromJson.getMsg()+listsize);


                } catch (IOException | JsonSyntaxException e) {
                    e.printStackTrace();
                }


            }

            return 200;
        }
    }


    /**
     * put 修改地址信息
     */
    public void putAddressinfo(String id,String name,String phone,String city,String detai) throws ExecutionException, InterruptedException {
        PutAddressinfo callableThread = new PutAddressinfo(id, name, phone, city, detai);
        FutureTask futureTask = new FutureTask<>(callableThread);
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
    }


    static class PutAddressinfo implements Callable {

         String id;
         String name;
         String phone;
         String city;
         String detai;

        public PutAddressinfo(String id, String name, String phone, String city, String detai) {
            this.id = id;
            this.name = name;
            this.phone = phone;
            this.city = city;
            this.detai = detai;
        }
        @Override
        public Object call() throws Exception {

            //url拼接
            String url =Apps.UpdateReserveInfo;
            Log.e("url", "-------------------------------------->" + url);

            //传递json
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", id);
            jsonObject.put("receiver", name);
            jsonObject.put("phone", phone);
            jsonObject.put("detaiAddress", detai);
            jsonObject.put("address",city );

            Log.e("AddressJSONTostring", "code------------------------------->"+jsonObject.toString() );
            String callStr = put(jsonObject.toString());
            JSONObject call_json = new JSONObject(callStr);

            final String code = call_json.getString("status");

            Log.e("UpdateAddress", "code------------------------------->"+code );

            System.out.println(Thread.currentThread().getName());

            return 200;
        }



        public   String put(String json) throws IOException {
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(Apps.UpdateReserveInfo)
                    .put(body)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                assert response.body() != null;
                String msg=response.body().string();
                Log.d("msg","msg---------------------------->"+msg );
                return msg;
            } else {
                throw new IOException("Unexpected code " + response);
            }

        }
    }

    /**
     * 删除数据 根据ID删除
     * @return
     * @param id
     */

    public void deleteAddress(String id){
        OkHttpDelete okHttpDelete=new OkHttpDelete(id);
        FutureTask futureTask = new FutureTask<>(okHttpDelete);
        new Thread(futureTask).start();
        try {
            System.out.println(futureTask.get());
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class OkHttpDelete implements Callable {

        String id;
        public OkHttpDelete(String id) {
            this.id = id;
        }
        @Override
        public Object call() throws Exception {

            Request request = new Request.Builder().url(Apps.DeleteReserveInfo+id).delete().build();
            Log.e("Delete", "--------------------------->"+Apps.DeleteReserveInfo+id);
            try (Response response = client.newCall(request).execute()) {
                assert response.body() != null;
                String msg=response.body().string();
                Log.e("Delete", "--------------------------->"+msg);
                return msg;
            }

        }
    }


}
